package com.example.demo.algorithm.symbol;

/**
 * @Author: xiatian
 * @CreateTime: 2022/1/10 2:54 下午
 * @Description:
 */
public class OrderSymbolTable<Key extends Comparable<Key>, Value> {
    //记录首节点
    private Node head;
    //记录符号表中的元素的个数
    private int N;

    public OrderSymbolTable() {
        head = new Node(null, null, null);
        N = 0;
    }

    /**
     * 符号表中键值对的个数
     *
     * @return
     */
    public int size() {
        return N;
    }

    //往符号表中插入键值对
    public void put(Key key, Value value) {
        Node pre = head;
        Node curr = head.next;
        while (curr != null) {
            //判断传入的key和当前节点的key的大小
            if (key.compareTo(curr.key) > 0) {
                pre = curr;
                curr = curr.next;
            }
            break;
        }
        //判断当前节点key是否和传入的key相等
        if (curr != null && curr.key.equals(key)) {
            curr.value = value;
            return;
        }
        Node newNode = new Node(key, value, curr);
        pre.next = newNode;
        N++;
    }

    public void delete(Key key) {
        Node n = head;
        while (n.next != null) {
            if (n.next.key.equals(key)) {
                n.next = n.next.next;
                N--;
                return;
            }
            n = n.next;
        }
    }

    public Value get(Key key) {
        Node curr = head.next;
        while (curr != null) {
            if (curr.key.equals(key)) {
                return curr.value;
            }
            curr = curr.next;
        }
        return null;
    }


    private class Node {
        private Key key;
        private Value value;
        public Node next;

        public Node(Key key, Value value, Node next) {
            this.key = key;
            this.value = value;
            this.next = next;
        }
    }

}
